package com.itheima.test3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class Server {
    public static void main(String[] args) throws IOException {
        //接收客户端上传的文件
        //创建ServerSocket对象并指定端口号
        ServerSocket ss = new ServerSocket(8888);
        //等待客户端连接并返回Socket对象
        Socket socket = ss.accept();
        //获取输入流对象
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //读取客户端发送的文件内容并保存到本地
        //获取唯一标识符，使得文件名不唯一
        String name = UUID.randomUUID().toString().replace("-", "");
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mysocketnet\\Serverdir\\" + name + ".jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            //将读取到的内容保存到本地文件
            bos.write(buffer, 0, len);
        }
        //回写数据
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("文件上传成功");
        bw.newLine();
        bw.flush();

        //释放资源
        socket.close();
        ss.close();


    }
}
